package com.site.blog.my.core.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: my-blog
 * @description:
 * @author: zxf
 * @create: 2021-06-30 09:13
 **/
@Component
public class AdminLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        if (uri.startsWith("/admin") && request.getSession().getAttribute("loginUser") == null){
            // 添加错误信息
            request.getSession().setAttribute("errorMsg","请登录");
            // 重定向到登录页面，防止重复提交
            response.sendRedirect(request.getContextPath()+"/admin/login");
            return false;
        }else{
            request.getSession().removeAttribute("errorMsg");
            return true;
        }
    }
}

